package com.mingtu.guards.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.Constant;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.AnimalBannerAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.AnimalResDetails;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AnimalDetailsActivity extends MyBaseActivity {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_ldname)
    TextView tvLdname;
    @BindView(R.id.tv_familyName)
    TextView tvFamilyName;
    @BindView(R.id.tv_genus)
    TextView tvGenus;
    @BindView(R.id.tv_details)
    TextView tvDetails;
    @BindView(R.id.tv_shape)
    TextView tvShape;
    @BindView(R.id.tv_habit)
    TextView tvHabit;
    @BindView(R.id.tv_settlement)
    TextView tvSettlement;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.layout_shape)
    LinearLayout layoutShape;
    @BindView(R.id.layout_habit)
    LinearLayout layoutHabit;
    @BindView(R.id.layout_settlement)
    LinearLayout layoutSettlement;
    @BindView(R.id.layout_details)
    LinearLayout layoutDetails;
    private ArrayList<LocalMedia> pictureList;
    private String resId;
    private AnimalBannerAdapter animalBannerAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_animal_details;
    }

    @Override
    protected void initView() {
        super.initView();
        setModuleTitle("生物详情");
    }

    @Override
    protected void initData() {
        resId = getIntent().getStringExtra("resId");
        String name = getIntent().getStringExtra("name");
        if (!StringUtils.isEmpty(resId)) {
            getDetails(resId);
        } else {
            ToastUtils.showLong(getResources().getString(R.string.data_error));
        }

        if (!StringUtils.isEmpty(resId)) {
            setModuleTitle(name);
        }
        initPullRefresh();

    }

    @Override
    protected void getData() {


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁
        if (banner != null) {
            banner.destroy();
        }
    }

    /**
     * 动物详情
     *
     * @param id
     */
    private void getDetails(String id) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", id);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_RES_DETAILS + "/" + id)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                AnimalResDetails animalResDetails = new AnimalResDetails();
                                animalResDetails = gson.fromJson(result, AnimalResDetails.class);

                                AnimalResDetails.ResAllBean resAllBean = animalResDetails.getResAll();

                                String name = resAllBean.getName();
                                String ldName = resAllBean.getLdName();
                                String familyName = resAllBean.getFamilyName();
                                String genus = resAllBean.getGenus();
                                String level = resAllBean.getLevel();
                                String shape = resAllBean.getShape(); //形态特征
                                String details = resAllBean.getDetails(); //生活习性
                                String habit = resAllBean.getHabit(); //分布范围
                                String settlement = resAllBean.getSettlement(); //栖息环境

                                List<AnimalResDetails.ResAllBean.ResAllPicsBean> resAllPicsBeans = resAllBean.getResAllPics();

                                if (resAllPicsBeans != null) {
                                    if (resAllPicsBeans.size() > 0) {
                                        int normalWidth = SizeUtils.dp2px(7);
                                        int selectedWidth = SizeUtils.dp2px(7);
                                        if (DeviceUtils.isTablet()) {
                                            normalWidth = SizeUtils.dp2px(14);
                                            selectedWidth = SizeUtils.dp2px(14);
                                        }

                                        IndicatorConfig.Margins margins = new IndicatorConfig.Margins();
                                        margins.bottomMargin = SizeUtils.dp2px(15);
                                        animalBannerAdapter = new AnimalBannerAdapter(context.getApplicationContext(), resAllPicsBeans);
                                        banner.setAdapter(animalBannerAdapter)
                                                .setIndicator(new CircleIndicator(context.getApplicationContext()), true)//设置指示器
                                                .setIndicatorNormalColor(context.getResources().getColor(R.color.white))
                                                .setIndicatorSelectedColor(context.getResources().getColor(R.color.colorPrimary))
                                                .setIndicatorNormalWidth(SizeUtils.dp2px(8))
                                                .setIndicatorSelectedWidth(SizeUtils.dp2px(8))
                                                .setIndicatorMargins(margins)
                                                .setIndicatorSpace(SizeUtils.dp2px(10))
                                                .setIndicatorGravity(IndicatorConfig.Direction.CENTER)
                                                .addBannerLifecycleObserver(AnimalDetailsActivity.this)//添加生命周期观察者
                                                .setOnBannerListener(new OnBannerListener() {
                                                    @Override
                                                    public void OnBannerClick(Object data, int position) {
                                                        if (pictureList != null) {
                                                            if (pictureList.size() > 0) {
                                                                BaseApplication.initPreviewModel().startActivityPreview(position, false, pictureList);
                                                            }
                                                        }
                                                    }
                                                });


                                        pictureList = new ArrayList<>();
                                        for (int i = 0; i < resAllPicsBeans.size(); i++) {
                                            String imgUrl = resAllPicsBeans.get(i).getUrl();
                                            LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(imgUrl);
                                            pictureList.add(localMedia);
                                        }

                                    }
                                }

                                if (!StringUtils.isEmpty(name)) {
                                    tvName.setText(name);
                                } else {
                                    tvName.setText("--");
                                }

                                if (!StringUtils.isEmpty(ldName)) {
                                    tvLdname.setText("拉丁学名：" + ldName);

                                }


                                tvLevel.setVisibility(View.GONE);
                                if (!StringUtils.isEmpty(level)) {
                                    tvLevel.setText("保护等级：" + level);
                                    tvLevel.setVisibility(View.VISIBLE);
                                }


                                if (!StringUtils.isEmpty(familyName)) {
                                    tvFamilyName.setText("科：" + familyName);
                                } else {
                                    tvFamilyName.setVisibility(View.GONE);
                                }
                                if (!StringUtils.isEmpty(genus)) {
                                    tvGenus.setText("属：" + genus);
                                } else {
                                    tvGenus.setVisibility(View.GONE);
                                }

                                if (!StringUtils.isEmpty(shape)) {
                                    tvShape.setText(shape + "");
                                } else {
                                    layoutShape.setVisibility(View.GONE);
                                }
                                if (!StringUtils.isEmpty(details)) {
                                    tvDetails.setText(details);
                                } else {
                                    layoutDetails.setVisibility(View.GONE);
                                }
                                if (!StringUtils.isEmpty(habit)) {
                                    tvHabit.setText(habit);
                                } else {
                                    layoutHabit.setVisibility(View.GONE);
                                }
                                if (!StringUtils.isEmpty(settlement)) {
                                    tvSettlement.setText(settlement);
                                } else {
                                    layoutSettlement.setVisibility(View.GONE);
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }


                        }
                    }
                });
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setEnableLoadMore(false);
        srlUp.setEnableOverScrollDrag(true);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                if (!StringUtils.isEmpty(resId)) {
                    getDetails(resId);
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}